package com.example.demo.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.study.mapper.SysUserMapper;
import com.example.demo.study.pojo.SysUser;
import com.example.demo.study.service.SysUserService;
import com.example.demo.study.utils.JwtUtil;
import com.example.demo.study.utils.LoginUser;
import com.example.demo.study.utils.RedisCache;
import com.example.demo.study.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author leo
 * @Date 2023/11/8 22:44
 * @Version 1.0
 */
@Service
public class SysUserServiceImpl implements SysUserService, UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public SysUser get(String userName) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userName);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if (sysUser == null) {
            throw new  RuntimeException("用户名或密码错误");
        }
        return sysUser;
    }

    @Override
    public ResponseResult login(SysUser user) {

        //用户认证
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassWord());
        Authentication authenticate = authenticationManager.authenticate(token);
        if (authenticate == null) {
            throw new RuntimeException("登录失败");
        }

        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();

        String userId = loginUser.getSysUser().getUserId();

        String jwt = JwtUtil.createJWT(userId);

        Map<String,String> map = new HashMap<>();

        map.put("token",jwt);

        redisCache.setCacheObject("login:"+userId,loginUser);

        return new ResponseResult(200,"登录成功",map);
    }

    @Override
    public int save(SysUser sysUser) {
        UpdateWrapper updateWrapper = new UpdateWrapper<SysUser>();
        if (sysUser.getUserId()==null){
            sysUser.setUserId(String.valueOf(IdWorker.getId()));
        }
        return sysUserMapper.update(sysUser,updateWrapper);
    }

    @Override
    public ResponseResult logout() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getSysUser().getUserId();
        redisCache.deleteObject("login:"+userId);
        return new ResponseResult(200,"注销成功");
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser sysUser = get(s);
        if (Objects.isNull(sysUser)) {
            throw new RuntimeException("用户名或密码错误");
        }
        return new LoginUser(sysUser);
    }
}
